package com.hyk.service.impl;

import com.google.common.collect.Lists;
import com.hyk.entity.Menu;
import com.hyk.entity.response.MenuListResponse;
import com.hyk.entity.response.Permission;
import com.hyk.mapper.MenuMapper;
import com.hyk.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hyk
 * @since 2021-03-16
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public void addMenu(Menu menu) {
        menuMapper.insert(menu);
    }

    @Override
    public List<MenuListResponse> selectMenu() {
        List<Menu> menus = menuMapper.selectMenuList();

        List<Menu> topNodes = Lists.newArrayList();
        for (Menu menu:menus){
            if (menu.getParentId() == -1){
                topNodes.add(menu);
            }
        }

        List<MenuListResponse> responses = topNodes.stream().map(menu -> {
            MenuListResponse menuListResponse = new MenuListResponse();
            BeanUtils.copyProperties(menu,menuListResponse);
            return menuListResponse;
        }).collect(Collectors.toList());

        List<MenuListResponse> recursion = recursion(responses, menus);

        return recursion;

    }

    @Override
    public List<Permission> getAllMenu() {
        return menuMapper.selectAllMenu();
    }

    @Override
    public List<Menu> findMenuByRole(String role) {
        return menuMapper.selectMenuByRole(role);
    }

    public List<MenuListResponse> recursion(List<MenuListResponse> responses,
                                            List<Menu> menus){
        for (MenuListResponse menuListResponse : responses){
            List<MenuListResponse> responsesx = Lists.newArrayList();
            for (Menu menu:menus){
                if (menu.getParentId().equals(menuListResponse.getId())){
                    MenuListResponse menuListResponsex = new MenuListResponse();
                    BeanUtils.copyProperties(menu,menuListResponsex);
                    menuListResponsex.setHasChildren(false);
                    responsesx.add(menuListResponsex);
                }
            }
            menuListResponse.setChildren(responsesx);
            if (!CollectionUtils.isEmpty(responsesx)){
                menuListResponse.setHasChildren(true);
                recursion(responsesx,menus);
            }
        }
        return responses;
    }
}
